package com.furnitur.modules.admin.controller.product;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.furnitur.common.annotation.MerchantOperation;
import com.furnitur.common.api.CommonResult;
import com.furnitur.common.enums.ResourceType;
import com.furnitur.core.entity.product.Furniture;
import com.furnitur.core.entity.user.User;
import com.furnitur.core.service.UserService;
import com.furnitur.modules.admin.dto.product.FurnitureDTO;
import com.furnitur.modules.admin.dto.product.FurnitureQueryDTO;
import com.furnitur.modules.admin.service.product.FurnitureService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping("/api/furniture")
@Validated
public class FurnitureController {
    private static final Logger log = LoggerFactory.getLogger(FurnitureController.class);
    
    @Autowired
    private FurnitureService furnitureService;
    
    @Autowired
    private UserService userService;
    
    @GetMapping("/list")
    public CommonResult<IPage<Furniture>> list(FurnitureQueryDTO queryDTO) {
        return CommonResult.success(furnitureService.list(queryDTO));
    }
    
    @GetMapping("/{id}")
    public CommonResult<Furniture> getDetail(@PathVariable Long id) {
        return CommonResult.success(furnitureService.getById(id));
    }
    
    @PostMapping
    @MerchantOperation(checkOwnership = false)
    public CommonResult<Void> create(@RequestBody @Valid FurnitureDTO furnitureDTO) {
        User currentUser = userService.getCurrentUser();
        log.info("Creating furniture for merchant: {}", currentUser);
        
        if (currentUser.getRoleId() != 2L) {
            log.warn("Non-merchant user attempting to create furniture: {}", currentUser);
            throw new RuntimeException("非商家用户无权操作");
        }
        
        furnitureService.create(furnitureDTO);
        return CommonResult.success(null);
    }
    
    @PutMapping("/{id}")
    @MerchantOperation(checkOwnership = true, resourceType = ResourceType.FURNITURE)
    public CommonResult<Void> update(@PathVariable Long id, @RequestBody @Valid FurnitureDTO furnitureDTO) {
        furnitureService.update(id, furnitureDTO);
        return CommonResult.success(null);
    }
    
    @DeleteMapping("/{id}")
    @MerchantOperation
    public CommonResult<Void> delete(@PathVariable Long id) {
        furnitureService.delete(id);
        return CommonResult.success(null);
    }
    
    @PutMapping("/{id}/status")
    @MerchantOperation
    public CommonResult<Void> updateStatus(@PathVariable Long id, @RequestParam Integer status) {
        furnitureService.updateStatus(id, status);
        return CommonResult.success(null);
    }
} 